package com.sample.springbatch.job.sample.writer;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemStream;
import org.springframework.batch.item.file.FlatFileFooterCallback;
import org.springframework.batch.item.file.FlatFileHeaderCallback;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor;
import org.springframework.batch.item.file.transform.DelimitedLineAggregator;
import org.springframework.core.io.PathResource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.Date;

/**
 * Flat文件格式写入类  实现了分隔符格式
 * Created by zwg on 2017/8/8.
 */
@Component
public class RepayOrderNewFlatFileItemWriter<RepayOrderInfo> extends FlatFileItemWriter {

    public static final Logger logger = LoggerFactory.getLogger(RepayOrderNewFlatFileItemWriter.class);

    public RepayOrderNewFlatFileItemWriter() {
        repayOrderOfDelimitedLine();
    }

    /**
     * 分隔符文件读取配置
     */
    private void repayOrderOfDelimitedLine() {
        //new ClassPathResource("jobdata/repay-orders_out.dat")
        setResource(new PathResource("target/data/repay-orders_out_0.dat"));
        setAppendAllowed(true);
        setLineAggregator(new DelimitedLineAggregator<RepayOrderInfo>(){{
            setDelimiter("|");
            setFieldExtractor(new BeanWrapperFieldExtractor<RepayOrderInfo>(){{
                setNames(new String[] { "userId", "productId","contractNo","amount","repayType","repayMethod" });
            }});
        }});

        /**
         * 写文件头
         */
        setHeaderCallback(new FlatFileHeaderCallback() {
            @Override
            public void writeHeader(Writer writer) throws IOException {
                writer.write("#begin time: "+ DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            }
        });

        /**
         * 写文件尾
         */
        setFooterCallback(new FlatFileFooterCallback() {
            @Override
            public void writeFooter(Writer writer) throws IOException {
                writer.write("#end time: "+ DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            }
        });
    }


    /**
     * Initialize the reader. This method may be called multiple times before
     * close is called.
     *
     * @param executionContext
     * @see ItemStream#open(ExecutionContext)
     */
    @Override
    public void open(ExecutionContext executionContext) {

        if(logger.isInfoEnabled()){
            logger.info("writer filePath:{}",System.currentTimeMillis());
        }

        super.open(executionContext);
    }
}
